<template>
  <!--      总库选择题目      -->
  <page-wrap back hide-tab title="面试选题" stay-still :bg-color="uNavColor">
    <InterViewNavbg />
    <view>
      <view class="search">
        <u-search
          placeholder="请输入题目标题"
          class="library-u-search"
          v-model="keyword"
          height="80"
          bg-color="#FFFFFF;"
          maxlength="20"
          :show-action="false"
          :clearabled="false"
          @search="handleSearch"
          @custom="handleSearch"
        ></u-search>
      </view>
      <scroll-view
        class="scrollView"
        scroll-y
        enable-flex
        @scrolltolower="loadMore"
        :refresher-triggered="triggered"
      >
        <!-- <QuestionCell
          v-for="(item, index) in list"
          :key="index"
          :itemObj="item"
          :index="index"
        >
        </QuestionCell> -->

        <view
          class="item-container"
          :class="
            selectedItemIds.includes(item.questionId) ? 'select-border' : ''
          "
          v-for="(item, index) in list"
          :key="index"
        >
          <view class="item-index-container" @click="clickCell(item)">
            <span class="item-index">{{ index | filterItemIndex }}</span>
            <!-- <image
              class="item-img"
              :src="modifyImg"
              @click="onClickModify"
            ></image>
            <image
              class="item-img"
              :src="deleteImg"
              @click="onClickDelete"
            ></image> -->
          </view>

          <view
            @click="clickCell(item)"
            class="item-title"
            :class="
              selectedItemIds.includes(item.questionId)
                ? 'select-title'
                : 'not-select-title'
            "
            >{{ item.questionTitle }}</view
          >
        </view>

        <u-loadmore
          v-if="list.length > 0 || !loaded"
          class="list-more"
          :status="moreLoading"
          :load-text="loadText"
        />
        <Empty
          v-if="loaded && list.length <= 0"
          :baseImg="emptyImg"
          text="暂无数据"
          :fontWeight="400"
        />
      </scroll-view>

      <view class="complete" @click="onClickComplete"> 完成 </view>
    </view>
  </page-wrap>
</template>

<script>
import QuestionCell from "./components/QuestionCell.vue";
import Empty from "@/components/Empty.vue";
import {
  getCompanyInterviewIssuesDB,
  batchCopyQuestionFromCommon,
  getCompanyRepoIds,
} from "@/api/modules/company";
import InterViewNavbg from "./components/InterViewNavbg.vue";
export default {
  components: {
    Empty,
    QuestionCell,
    InterViewNavbg,
  },
  data() {
    return {
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      companyId: uni.getStorageSync("company-id"),
      //companyId: "1001",
      //personId: 2,

      ylPositionId: undefined,
      //ylPositionId:'273875',
      showQuestions: false,
      keyword: "",
      list: [],
      selectedItemIds: [],

      pageParams: {
        pageNo: 1,
        pageSize: 10,
      },
      emptyImg: this.$imgBaseSelf + "common/empty.png",
      selectedIcon: this.$imgBaseSelf + "library/selected.png",

      loading: false,
      moreLoading: "loadmore",
      loadText: {
        loadmore: "加载更多",
        loading: "加载中",
        nomore: "已经到底啦",
      },
      loaded: false,

      modifyImg:
        this.$imgBaseSelf + "interview/icon-interview-question-modify.png",

      deleteImg:
        this.$imgBaseSelf + "interview/icon-interview-question-delete.png",
    };
  },
  onLoad(options) {
    if (options) {
      if (options.repoId) {
        this.repoId = options.repoId;
      }
      if (options.ylPositionId) {
        this.ylPositionId = options.ylPositionId;
      }
      // if(options.ids){
      //   const ids = JSON.parse(options.ids)
      //   this.selectedItemIds = ids;
      // }
    }

    this.getRepoIds();
    this.getData(false);
  },

  filters: {
    filterItemIndex(val) {
      var num = val + 1;
      if (num == 10) {
        return "问题" + "十";
      } else if (num == 1) {
        return "问题" + "一";
      }
      const digits = [
        "零",
        "一",
        "二",
        "三",
        "四",
        "五",
        "六",
        "七",
        "八",
        "九",
      ];
      const units = ["", "十", "百", "千", "万"];
      let result = "";
      let numStr = num.toString();
      for (let i = 0; i < numStr.length; i++) {
        let digit = parseInt(numStr.charAt(i));
        let unit = units[numStr.length - i - 1];
        if (digit === 0) {
          // 当前数字为0时不需要输出汉字，但需要考虑上一个数字是否为0，避免出现连续的零
          if (result.charAt(result.length - 1) !== "零") {
            result += "零";
          }
        } else {
          result += digits[digit] + unit;
        }
      }
      // 对于一些特殊的数字，如10、100等，需要在最前面加上“一”
      if (result.charAt(0) === "一") {
        result = result.substr(1, result.length);
      } else if (result.charAt(0) === "百") {
        result = "一" + result;
      } else if (result.charAt(0) === "千") {
        result = "一" + result;
      }
      return "问题" + result;
    },
  },

  methods: {
    loadMore() {
      this.getData(true);
    },
    onRestore() {
      this.triggered = false;
      this._triggered = false;
    },
    onRefresh() {
      if (this._triggered) return;
      this._triggered = true;

      if (!this.triggered) {
        this.triggered = true;
      }
      this.getData(false);
    },

    handleSearch(value) {
      this.keyword = value;
      this.getData(false);
    },

    // 添加/删除题目
    clickCell(item) {
      let questionId = item.questionId;
      var a = this.selectedItemIds;

      const hasSameElement = a.includes(questionId);
      if (hasSameElement) {
        const index = a.indexOf(questionId);
        a.splice(index, 1);
      } else {
        a.push(questionId);
      }
    },

    // 获取全部面试题
    getData(isMore) {
      if (this.moreLoading == "loading") return;
      if (this.moreLoading == "nomore" && isMore) {
        return;
      }
      if (!isMore) {
        this.pageParams.pageNo = 1; // 刷新数据
      }
      const params = {
        pageNo: this.pageParams.pageNo,
        pageSize: this.pageParams.pageSize,
        companyId: this.companyId,
        questionTitle: this.keyword,
        ylPositionId: this.ylPositionId,
        repoId: this.repoId,
      };
      this.moreLoading = "loading";

      getCompanyInterviewIssuesDB(params)
        .then((res) => {
          console.log(
            "🚀 ~ file: selectInterviewQuestions.vue:255 ~ .then ~ res:",
            res
          );
          this.moreLoading = "loadmore";
          this.loaded = true;
          if (res.code == 200) {
            if (isMore) {
              this.list.push(...res.data);
            } else {
              this.list = res.data;
            }

            // const result = res.data.filter(item => item.isSelected === 2); //  1未选中，2已选中
            // result.forEach(element => {
            //   this.clickCell(element);
            // });

            this.pageParams.pageNo++;
            if (this.pageParams.pageNo > res.pageparam.pages) {
              this.moreLoading = "nomore";
            }
          } else {
            this.moreLoading = "nomore";
            uni.showToast({
              title: res.status_desc,
              icon: "none",
            });
          }
        })
        .catch((e) => {
          console.log(e);
          this.moreLoading = "nomore";
        })
        .finally(() => {
          this.triggered = false;
          this._triggered = false;
        });
    },

    // 获取所有选中题目ID
    getRepoIds() {
      const params = {
        repoId: this.repoId,
      };
      getCompanyRepoIds(params).then((res) => {
        console.log(
          "🚀 ~ file: selectInterviewQuestions.vue:296 ~ .then ~ res:",
          res
        );
        if (res.code == 200) {
          this.selectedItemIds = res.data;
        }
      });
    },

    // 完成创建
    onClickComplete() {
      if (!this.ylPositionId) {
        return;
      }
      if (this.selectedItemIds.length == 0) {
        uni.showToast({
          title: "请选择面试题目",
          icon: "none",
        });
        return;
      }

      const params = {
        requestIdList: this.selectedItemIds,
        ylPositionId: this.ylPositionId,
        repoId: this.repoId,
        companyId: this.companyId,
        userId: this.personId,
      };

      batchCopyQuestionFromCommon(params)
        .then((res) => {
          uni.showToast({
            title: res.status_desc,
            icon: "none",
          });
          if (res.code == 200) {
            uni.navigateBack({ delta: 1 });
          } else {
          }
        })
        .catch((e) => {})
        .finally(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.item-img {
  height: auto;
  width: 32rpx;
  padding-left: 10rpx;
  padding-right: 10rpx;
}

.select-border {
  border: 2rpx solid #f75a3e;
}

.select-title {
  color: #f75a3e;
}

.not-select-title {
  color: #222222;
}

.item-container {
  padding-left: 36rpx;
  padding-right: 36rpx;
  //align-items: center;
  justify-content: center;
  background: #ffffff;
  border-radius: 24rpx;
  margin-left: 32rpx;
  margin-right: 32rpx;
  margin-top: 16rpx;
  // height: 148rpx;
  display: flex;
  flex-direction: column;

  .item-index-container {
    display: flex;
    flex-direction: row;
    margin-top: 26rpx;
    .item-index {
      flex: 1;
      color: #999999;
      font-size: 22rpx;
    }
  }

  .item-title {
    margin-top: 10rpx;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    // -webkit-line-clamp: 1;
    overflow: hidden;
    font-size: 32rpx;
    // font-weight: bolder;
    margin-bottom: 26rpx;
  }
}

.search {
  margin: 32rpx 32rpx 10rpx;
}

.scrollView {
  box-sizing: border-box;
  height: calc(100vh - 88rpx - 200rpx - 96rpx - 100rpx);
}

.complete {
  color: #ffffff;
  width: 424rpx;
  display: flex;
  flex-direction: row;
  background: #f75a3e;
  border-radius: 44rpx;
  font-size: 28rpx;
  line-height: 88rpx;
  height: 88rpx;
  justify-content: center;
  align-items: center;
  position: absolute;
  bottom: 96rpx;
  z-index: 2;
  left: calc(50vw - 200rpx);
}
</style>
